/**
 * 
 */
package org.mspring.mlog.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Calendar;

import org.mspring.mlog.core.ServiceFactory;
import org.mspring.platform.utils.ImageUtils;
import org.mspring.platform.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Gao Youbo
 * @since 2013-6-3
 * @description
 * @TODO 头像处理相关操作
 */
public class AvatarUtils {

    public static final String AVATAR_NAME_PREFIX = "avatar-";

    /**
     * 获取用户头像名称
     * 
     * @param userid
     * @return
     */
    public static String getAvatarFilename(Long userid) {
        return AVATAR_NAME_PREFIX + userid;
    }

    /**
     * 获取当前图像应该保存的文件夹位置
     * 
     * @return
     */
    public static String getAvatarFoldername() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        return "/avatar/" + year + "/" + month + "/";
    }

    /**
     * 获取零时文件路径
     * 
     * @return
     */
    public static String getAvatarTempFilename(Long userid) {
        return getAvatarFilename(userid) + "_temp";
    }

    /**
     * 上传图像文件
     * 
     * @param mf
     * @param userid
     * @return 上传后的图片路径
     */
    public static String uploadAvatar(MultipartFile mf, Long userid) {
        if (mf == null || userid == null) {
            return null;
        }
        String filename = getAvatarFoldername() + getAvatarTempFilename(userid) + "." + StringUtils.getFileExtend(mf.getOriginalFilename());
        try {
            return ServiceFactory.getFileService().uploadFile(filename, mf.getInputStream());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 图片剪裁
     * 
     * @param file
     *            要剪切的图片
     * @param userid
     *            用户ID
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @return 剪切后图片的路径
     */
    public static String cropAvatar(File file, Long userid, int startX, int startY, int endX, int endY) {
        String filename = WebUtils.getRealContextPath("/uploads") + getAvatarFoldername() + getAvatarFilename(userid) + "." + StringUtils.getFileExtend(file.getName());
        try {
            BufferedImage image = ImageUtils.crop(file, startX, startY, endX, endY);
            // ImageIO.write(image, StringUtils.getFileExtend(file.getName()),
            // filename);
            return null;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }
}
